/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 *
 *PmPurchaseApplyController
 * 采购申请
 *
 * 修改纪录
 * 2020-05-09 版本：1.0 shenyouyi 创建。
 * @version 版本：1.0
 * @author 作者：shenyouyi
 * 创建日期：2020-05-09
 */

package com.topscomm.pm.controller;

import com.topscomm.app.service.IAppPageService;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.pm.controller.auto.PmPurchaseApplyControllerAuto;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst;
import java.util.HashMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: shenyouyi
 * @date: 2020-05-09
 * @description:采购申请Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/purchaseApply")
public class PmPurchaseApplyController extends PmPurchaseApplyControllerAuto implements IPmPurchaseApplyController {

	@Resource(name = "appPageService")
	private IAppPageService appPageService;

	/**
	 * @author: shenyouyi
	 * @date: 2020-05-09
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_projectid")) {
			String value = paraMap.get("qry_projectid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmPurchaseApply.projectid = {0} ", value);
		}
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmPurchaseApply.name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_companyname")) {
			String value = paraMap.get("qry_companyname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmPurchaseApply.companyname like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmPurchaseApply.code = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmPurchaseApply.state={0}", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmPurchaseApply.docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmPurchaseApply.docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmPurchaseApply.docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		sql .appendSingle(this.spellingSqlForProject(paraMap, "PmPurchaseApply","projectid","id"));
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession)) {
				sql.appendSingle(" and (" + MisStringUtil.createWhereByUsercodeFromProject(
						this.getUserBean().getUser(), "projectid",
						service.getDao().getTableName()) +
								" or PmPurchaseApply.usercode = '{0}')",
						this.getUserBean().getUser().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @author: shenyouyi
	 * @date: 2020-05-09
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: shenyouyi
	 * @date: 2020-05-11
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交采购申请申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
		List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmPurchaseApply", dataMap.get("deptcode").toString(),dataMap.get("usercode").toString(),null, "sortcode");
		Long flowid = flowidList.size()>0? ConvertUtil.convertToLong(flowidList.get(0).get("id")) :null;
		dataMap.put("flowid", flowid);

	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 取消审批
	  **/
	@DeleteMapping({"/delApproval"})
	public ResponseResult<Object> delApproval(@RequestBody(required = false) Map<String, Object> paraMap) {
		ResponseResult responseResult = super.delApproval(paraMap);
		if(responseResult.isSuccess()){
			String id = ConvertUtil.convertToString(paraMap.get("id"));
			this.service.updatePurchasemoneyOfProjectBase(id, false);
			return ResponseResult.ok("取消审批成功");
		}
		return responseResult;
	}




	@Override
	@GetMapping({"/list"})
	public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			paraMap.put("whereSql",sqlWhere);
			int totalCount = this.service.getCount(paraMap,"getPmPurchaseApplyAndProjectCount");
			List<Map<String, Object>> tempList = null;
			HashMap<String, Object> paraMap2 = new HashMap<>();
			paraMap2.put("curPageIndex",query.getCurrentPage());
			int beginCount=query.getCurrentPage()*query.getPageSize()-query.getPageSize();
			paraMap2.put("begincount",beginCount);
			paraMap2.put("pagesize", query.getPageSize());
			paraMap2.put("sidx", query.getSidx());
			paraMap2.put("sord", query.getSord());
			paraMap2.put("whereSql", sqlWhere);
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPage(paraMap2,"getPmPurchaseApplyAndProject");
			} else {
				tempList = this.service.queryMap(paraMap2,"queryMapByWhere1");
			}
			this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}


	/**
	 * liwanpeng
	 * 手机端采购申请，详情信息
	 * @param paraMap
	 * @return
	 * @throws IOException
	 * @throws SQLException
	 */
//	@GetMapping(value = "/loadMobilePageInfo")
//	public ResponseResult<Object> loadMobilePageInfo(@RequestParam(required = false) Map<String, Object> paraMap) throws SQLException, IOException {
//		paraMap = BaseUtil.decodeSecureMap(paraMap);
//		Map<String, Object> dataMap = this.service.queryMapById(paraMap.get("id").toString());
//		afterLoad(dataMap);
//		String jsonstr=JSON.toJSONStringWithDateFormat(dataMap,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteDateUseDateFormat);
//		dataMap = JSON.parseObject(jsonstr,Map.class);
//		Map<String,Object> myDadaMap = new HashMap<>();
//		Map<String, Object> mainTab = this.service.queryMapById(paraMap.get("id").toString());
//		List<Map<String, Object>> mainList = new ArrayList<>();
//		mainList.add(mainTab);
//		myDadaMap.put("PmPurchaseApply",mainList);
//		appPageService.getPageInfo("PmPurchase", myDadaMap);
//		return ResponseResult.ok(myDadaMap);
//	}
//	public void splitDataMap(Map<String,Object> myDadaMap) {
//		List<Map<String, String>> datalist =new ArrayList<>();
//		if (myDadaMap.containsKey("leadBackBoneTab")) {
//			 datalist=((List<List<Map<String, String>>>) myDadaMap.get("leadBackBoneTab")).get(0);
//				manageMap(datalist);
//		}
//
//
//		if (myDadaMap.containsKey("chanceBackTab")) {
//			 datalist=((List<List<Map<String, String>>>) myDadaMap.get("chanceBackTab")).get(0);
//			 manageMap(datalist);
//		}
//
//	}
//	public void manageMap(List<Map<String, String>> datalist ) {
//		if (datalist!=null) {
//			String json =JSON.toJSONString(datalist);
//			List<Map<String, String>> datalistnew = new ArrayList<>();
//			int index=0;
//			for (int j = 0; j < datalist.size(); j++) {
//				Map<String, String> mymap =datalist.get(j);
//				if (mymap.get("key").equals("resemble_id_array")) {
//					index = j;
//					String ids = mymap.get("oriValue");
//					ids=ids+",";
//					String[] idStrings = ids.split(",");
//					for(int i=0;i<idStrings.length;i++) {
//						Map<String, String> map= new HashMap<>();
//						map.putAll(mymap);
//						String extendJson=	map.get("extendfield3");
//						Map<String, String> extendMap =JSON.parseObject(extendJson,Map.class);
//						if (idStrings.length==1) {
//							extendMap.put("titleKey", extendMap.get("titleKey")+":");
//						}else {
//							extendMap.put("titleKey", extendMap.get("titleKey")+(i+1)+":");
//						}
//						extendJson = JSON.toJSONString(extendMap);
//						map.put("extendfield3", extendJson);
//						if (idStrings.length==1) {
//							map.put("disTitle", map.get("disTitle"));
//						}else {
//							map.put("disTitle", map.get("disTitle")+(i+1));
//						}
//
//						map.put("oriValue", idStrings[i]);
//						map.put("value", idStrings[i]);
//						datalistnew.add(map);
//					}
//					break;
//				}
//
//			}
//			if (datalistnew.size()!=0) {
//				datalist.remove(index);
//				datalist.addAll(index,datalistnew);
//			}
//		}
//	}
}

